import 'package:dotted_border/dotted_border.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:syncfusion_flutter_pdfviewer/pdfviewer.dart';
import 'package:syncfusion_flutter_signaturepad/signaturepad.dart';
import 'dart:ui' as ui;

import '../../config/draw.dart';
import '../../config/glass_ui.dart';
import '../../config/screen_util.dart';

class FreeAppliedPage extends StatefulWidget {
  const FreeAppliedPage({super.key});

  @override
  State<FreeAppliedPage> createState() => _FreeAppliedPageState();
}

class _FreeAppliedPageState extends State<FreeAppliedPage> {
  bool hasImage = false;
  bool _isBur = true;
  Image? signature;
  Offset updateMoveOffset =
      Offset(ScreenUtil().setHeight(100), ScreenUtil().setHeight(100));

  Offset startMoveOffset =
      Offset(ScreenUtil().setHeight(100), ScreenUtil().setHeight(100));

  Offset endMoveOffset =
      Offset(ScreenUtil().setHeight(100), ScreenUtil().setHeight(100));

  void _handleSignatureButtonPressed() async {
    var image = await Navigator.of(context).push(
        MaterialPageRoute(builder: (context) => const SignaturePadPage()));
    print(image);
    if (image != null) {
      setState(() {
        hasImage = true;
        signature = image as Image;
      });
    }
  }

  Widget buildSignature() {
    return Transform.translate(
        offset: updateMoveOffset,
        child: GestureDetector(
          behavior: HitTestBehavior.opaque,
          child: Column(
            children: [
              TextButton(
                  style: ButtonStyle(
                    // shape: MaterialStateProperty.all(value),
                    //设置水波纹颜色
                    overlayColor: MaterialStateProperty.all(Colors.red[300]),
                    backgroundColor: MaterialStateProperty.all(Colors.red),
                      shape: MaterialStateProperty.all(
                        const RoundedRectangleBorder(
                          borderRadius: BorderRadius.all(Radius.circular(0)),
                        ),
                      ),
                  ),
                  onPressed: () {
                    print("sss");
                    setState(() {
                      hasImage = false;
                    });
                  },

                  child: const Text(
                    '删除',
                    style: TextStyle(color: Colors.white),
                  )),
              DottedBorder(
                borderType: BorderType.RRect,
                color: _isBur ? Colors.grey : Colors.transparent,
                dashPattern: const [4, 4, 4, 4],
                radius: const Radius.circular(12),
                child: GlassMorphism(
                    blur: _isBur ? 1 : 0,
                    opacity: _isBur ? 0.4 : 0,
                    child: SizedBox(
                      height: 200.h,
                      width: 600.w,
                      child: signature,
                    )),
              )
            ],
          ),
          // 需要移动的组件
          onPanStart: (details) {
            startMoveOffset = details.localPosition;
            setState(() {
              _isBur = true;
            });
          },
          onPanUpdate: (details) {
            Offset intervalOffset =
                details.localPosition - startMoveOffset + endMoveOffset;
            setState(() {
              updateMoveOffset = intervalOffset; // 更新坐标
            });
          },
          onPanEnd: (details) {
            endMoveOffset = updateMoveOffset;
          },
          onTap: () {
            print("1231232");
            setState(() {
              _isBur = true;
            });
          },
        ));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          GestureDetector(
            // behavior: HitTestBehavior.opaque,
            onTap: () {
              print("pdffasdfass");
              setState(() {
                _isBur = false;
              });
            },
            child: SfPdfViewer.network(
                'https://cdn.syncfusion.com/content/PDFViewer/flutter-succinctly.pdf',
                scrollDirection: PdfScrollDirection.horizontal,
                canShowSignaturePadDialog: true),
          ),
          TextButton(
            style: ButtonStyle(
              backgroundColor: MaterialStateProperty.all(Colors.blue),
            ),
            onPressed: _handleSignatureButtonPressed,
            child: const Text(
              '签名',
              style: TextStyle(color: Colors.white),
            ),
          ),
          hasImage
              ? buildSignature()
              : const SizedBox(
                  height: 0,
                )
        ],
      ),
      // SignaturePadPage(),
    );
  }
}

class SignaturePadPage extends StatefulWidget {
  const SignaturePadPage({Key? key}) : super(key: key);

  @override
  _SignaturePadPageState createState() => _SignaturePadPageState();
}

class _SignaturePadPageState extends State<SignaturePadPage> {
  final GlobalKey<SfSignaturePadState> signatureGlobalKey = GlobalKey();

  @override
  void initState() {
    super.initState();
    AppUtil().setScreenLandscape(true);
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    AppUtil().setScreenLandscape(false);
  }

  void _handleClearButtonPressed() {
    signatureGlobalKey.currentState!.clear();
  }

  void _handleSaveButtonPressed() async {
    final data =
        await signatureGlobalKey.currentState!.toImage(pixelRatio: 3.0);
    final bytes = await data.toByteData(format: ui.ImageByteFormat.png);
    // Navigator.of(context).push(
    //   MaterialPageRoute(
    //     builder: (BuildContext context) {
    //       return Scaffold(
    //         appBar: AppBar(),
    //         body: Center(
    //           child: Container(
    //             color: Colors.grey[300],
    //             child: Image.memory(bytes!.buffer.asUint8List()),
    //           ),
    //         ),
    //       );
    //     },
    //   ),
    // );
    Navigator.of(context).pop(Image.memory(bytes!.buffer.asUint8List()));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text(
            "请在虚线框内签字",
            style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
          ),
        ),
        body: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            DottedBorder(
                borderType: BorderType.RRect,
                color: Colors.grey,
                dashPattern: const [4, 4, 4, 4],
                radius: const Radius.circular(12),
                child: Padding(
                    padding: const EdgeInsets.all(0),
                    child: Container(
                        // color: Colors.red,
                        height: ScreenUtil().setHeight(1000),
                        width: ScreenUtil().setWidth(1000),
                        // decoration:
                        // BoxDecoration(border: Border.all(color: Colors.grey)),
                        child: SfSignaturePad(
                            key: signatureGlobalKey,
                            backgroundColor: Colors.transparent,
                            strokeColor: Colors.black,
                            minimumStrokeWidth: 1.0,
                            maximumStrokeWidth: 4.0)))),
            // const SizedBox(height: 10),
            Row(mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [
              TextButton(
                style: ButtonStyle(
                  backgroundColor: MaterialStateProperty.all(Colors.blue),
                ),
                onPressed: _handleSaveButtonPressed,
                child: const Text(
                  '保存',
                  style: TextStyle(color: Colors.white),
                ),
              ),
              TextButton(
                style: ButtonStyle(
                  backgroundColor: MaterialStateProperty.all(Colors.grey),
                ),
                onPressed: _handleClearButtonPressed,
                child: const Text('删除', style: TextStyle(color: Colors.white)),
              ),
            ])
          ],
        ));
  }
}
